package controller;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.Session;
import db.Hooldusteenus;
import db.HooldusteenuseTellimus;
import db.Kinnistu;

public class FormUtil {
    
    public static HooldusteenuseTellimus getTellimusFromRequest(HttpServletRequest request, Session s){
	HooldusteenuseTellimus t = new HooldusteenuseTellimus();
	t.setAiaPindala(getBigDecimal(request.getParameter("aed")));
	if(StringUtils.isNotBlank(request.getParameter("algus"))){
	    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
	   try {
	    t.setRegistrAeg(format.parse(request.getParameter("algus")));
	} catch (ParseException e) {
	    e.printStackTrace();
	}
	}
	if(request.getParameter("kinnistu") != null){	    
	    Integer id = Integer.valueOf(request.getParameter("kinnistu"));
	    t.setKinnistu((Kinnistu) s.load(Kinnistu.class, id));
	}
	if(request.getParameter("teenus") != null){
	    Integer id = Integer.valueOf(request.getParameter("teenus"));
	    t.setHooldusteenus((Hooldusteenus) s.load(Hooldusteenus.class, id));
	}	
	t.setSiseruumidePindala(getBigDecimal(request.getParameter("sise")));
	
	if(StringUtils.isNotBlank(request.getParameter("tubadeArv"))){
	    Integer id = Integer.valueOf(request.getParameter("tubadeArv"));
	    t.setTubadeArv(id);
	}
	t.setKommentaar(request.getParameter("markused"));
	return t;
    }
    
    private static BigDecimal getBigDecimal(String s){
	if(StringUtils.isBlank(s)){
	    return null;
	}
	s = s.replace(",",".");
	return new BigDecimal(s);
    }

}
